//
//  UserRequest.m
//  SleepingElf
//
//  Created by karong on 2023/10/24.
//

#import "UserRequest.h"

@implementation UserRequest
+ (void)loginWithSuccess:(AnyObjectBlock)success failed:(Failure)failed {
    NSString * url = API_USER_LOGIN;
    NSDictionary * parameters = @{@"token":SEEmptyStr(appUserCenter.qtoken)};
    [self postWithURLString:url parameters:parameters success:^(NSDictionary * _Nonnull responseDict) {
        SEUserCenter * userCenter = [SEUserCenter mj_objectWithKeyValues:responseDict[@"data"]];
        [appUserCenter logIn:userCenter];
        [[NSNotificationCenter defaultCenter]postNotificationName:SELoginSuccessNotification object:nil];
        success(userCenter);
    } failure:failed];
}

+ (void)getUserInfoWithUser_id:(NSInteger)user_id success:(AnyObjectBlock)success failed:(Failure)failed {
    NSString * url = API_USER_INFO;
    NSDictionary * parameters = @{@"user_id":@(user_id)};
    [self postWithURLString:url parameters:parameters success:^(NSDictionary * _Nonnull responseDict) {
        SEUserCenter * user = [SEUserCenter mj_objectWithKeyValues:responseDict];
        success(user);
    } failure:failed];
}

+ (void)editUserInfoWithNickname:(NSString *)nickname success:(EmptyBlock)success failed:(Failure)failed {
    NSString * url = API_USER_EDIT;
    NSDictionary * parameters = @{@"nickname":SEEmptyStr(nickname),
    };
    [self postWithURLString:url parameters:parameters success:^(NSDictionary * _Nonnull responseDict) {
        success();
    } failure:failed];
}

+ (void)uploadImage:(UIImage *)image success:(StringBlock)success failed:(Failure)failed {
    NSString *url = API_UPLOAD_IMAGE;
    NSDictionary * parameters = @{};
    NSData *data =UIImageJPEGRepresentation(image, 0.6) ;// UIImageJPEGRepresentation([UIImage fixOrientationImage:image], 0.8);
    if (data == nil) {
        data = UIImagePNGRepresentation(image);
    }
    if (!data) {
        return;
    }
    // 設置時間格式
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyyMMddHHmmss"];
    NSString *dateString = [formatter stringFromDate:[NSDate date]];
    NSString *fileName = [NSString stringWithFormat:@"%@.jpg", dateString];
    [self postWithURLString:url parameters:parameters fileDatas:@[data] fileNames:@[fileName] success:^(NSDictionary *responseDict) {
        NSDictionary * date = responseDict[@"data"];
        NSString *imageURLString = date[@"fileUrl"];
        if (SEIsNullOrEmpty(imageURLString)) {
            [SEToast simple:WSLocalized(@"圖片上傳失敗，請重新選擇")];
        }
        else {
            success(imageURLString);
        }
    } failure:failed];
}

+ (void)delUserWithSuccess:(EmptyBlock)success failed:(Failure)failed {
    NSString * url = API_USER_DEL;
    NSDictionary * parameters = @{};
    [self postWithURLString:url parameters:parameters success:^(NSDictionary * _Nonnull responseDict) {
        [appUserCenter logOut];
        success();
    } failure:failed];
}
@end
